package getDataFromAciveMQ;

import java.util.ArrayList;
import java.util.List;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQQueue;
import org.json.JSONObject;

import pojo.Book;
import util.ActiveMqUtil;
import dao.impl.BookDaoImpl;

public class GetDataFromAciveMQTread extends Thread{
	private Connection con;
	private Destination queue;
	private BookDaoImpl impl;
	private MessageConsumer consumer;
	public GetDataFromAciveMQTread() throws JMSException{
		impl = new BookDaoImpl();
		queue = new ActiveMQQueue("matthew");
		con = ActiveMqUtil.createConnection();
		con.start();
		Session sen = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
	    consumer = sen.createConsumer(queue);
	}
		
	@Override
	public void run() {
		JSONObject json = null;
		String jsonString = null;
		List<Book> books = new ArrayList<Book>();
		int i = 1;
		try {
			while(i++ <= 10000){
				TextMessage msg = (TextMessage) consumer.receive();
				jsonString = msg.getText();
				Book book = impl.transferJsonToBook(jsonString);
				books.add(book);
				
				if(books.size() % 200 == 0){
					impl.addBookList(books);
					books.clear();
				}
			}
			
			impl.addBookList(books);
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
